import { getCartList, changeCount, delCartGoods } from '@/api/cart'
export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  mutations: {
    // 给购物车列表赋值
    setCartList (state, newList) {
      state.cartList = newList
    },
    // 切换复选框状态
    toggleChecked (state, goodsId) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.isChecked = !goods.isChecked
    },
    // 全选，反选控制
    allCheckedHandle (state, flag) {
      state.cartList.forEach(item => (item.isChecked = flag))
    },
    // 更新商品数量
    setCount (state, newCount) {
      state.cartList.goods_num = newCount
    },
    // 更新商品数量
    changeCount (state, { goodsId, goodsNum }) {
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.goods_num = goodsNum
    }
  },
  actions: {
    // 获取购物车列表
    async getCartListAction (context) {
      const res = await getCartList()
      res.data.list.forEach(item => {
        item.isChecked = true
      })
      context.commit('setCartList', res.data.list)
    },
    // 更新购物车商品数量
    async changeCountAction (context, obj) {
      // 先本地修改
      context.commit('changeCount', obj)
      context.state.cartList.find(item => item.goods_id === obj.goodsId).goods_num = obj.goodsNum
      // 再同步到后台
      await changeCount(obj.goodsId, obj.goodsNum, obj.goodsSkuId)
    },
    // 删除购物车商品
    async delCartGoodsAction (context) {
      // 删除后台的商品
      const list = context.getters.selCartList
      const cartIds = list.map(item => item.id)
      await delCartGoods(cartIds)
      // 更新物品
      context.dispatch('getCartListAction')
    }
  },
  getters: {
    // 所有商品累加总数
    cartTotal (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 选中的商品列表
    selCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    // 选中商品的价格
    selPrice (state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + (item.goods.goods_price_min * item.goods_num), 0).toFixed(2)
    },
    // 选中商品的数量
    selCount (state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + (+item.goods_num), 0)
    },
    // 判断全选复选框是否打勾
    allChecked (state) {
      return state.cartList.length > 0 ? state.cartList.every(item => item.isChecked) : 0
    }
  }
}
